<template>
  <div class="content">
    <!-- 筛选 -->
    <el-card class="box-card select-card text-align-start">
      <el-input v-model="select.mmsi"  placeholder="请输入船舶MMSI"clearable class="common-style"></el-input>
      <el-input v-model="select.algorithmId"  placeholder="请输入告警编码"clearable  class="common-style"></el-input>
      <el-input v-model="select.cameraName"  placeholder="请输入摄像头位置"clearable  class="common-style"></el-input>
      <el-select v-model="select.deptName" placeholder="请选择船舶" clearable class="common-style">
        <el-option v-for="item in shipOptions" :key="item.deptName" :label="item.deptName" :value="item.deptName" />
      </el-select>
      <el-select v-model="select.algorithmName" placeholder="请选择告警类型" clearable class="common-style">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="select.level" placeholder="请选择告警等级" clearable class="common-style">
        <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="select.state" placeholder="请选择告警状态" clearable class="common-style">
        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-date-picker v-model="select.date" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd" :clearable="false"
        style="width: 376px; margin-right: 10px; margin-top: 10px;" />
      <!-- :default-time="['00:00:00', '23:59:59']" HH:mm:ss -->
      <el-button type="primary" @click="clickReset" v-loading.fullscreen.lock="fullscreenLoading" style="margin-top: 10px;">重置</el-button>
      <el-button type="primary" @click="clickSelect" v-loading.fullscreen.lock="fullscreenLoading" style="margin-top: 10px;">查询</el-button>
      <el-button type="primary" @click="exportExcel" style="margin-top: 10px;">导出</el-button>
    </el-card>
    <div class="card-content head-card">
      <div class="head-card-icon-box">
        <i class="el-icon-s-fold" :class="isTable ? 'active' : ''" @click="handleTypeView(true)" />
        <i class="el-icon-s-grid" :class="!isTable ? 'active' : ''" @click="handleTypeView(false)" />
      </div>
      <div v-if="!isTable" style="width: 100%;margin-right: 16px;">
        <div class="alarm-popup" v-if="alarmPopupList.length > 0">
          <div class="popup-item" v-for="(item, index) in alarmPopupList" :key="index" @click="clickVisibleImgae(item)"
            style="cursor: pointer">
            <img :src="domain + item.img_name" />
            <div class="popup-title">
              告警类型:
              <span style="color: red">&nbsp;&nbsp;{{ item.algorithm_name }}</span>
            </div>
            <div class="popup-tips">
              <span style="font-weight: bold; color: #333">告警时间: &nbsp;&nbsp;</span>{{ item.alarm_dt }}
            </div>
            <div class="popup-tips">
              <span style="font-weight: bold; color: #333">告警状态: &nbsp;&nbsp;</span>{{ item.state == 1 ? '正常' : '误检' }}
              <el-button class="state-btn" @click.stop="clickFeedback(item)" v-if="item.state == 1"
                size="mini">反馈</el-button>
            </div>
            <div class="popup-tips">
              <span style="font-weight: bold; color: #333">摄像头位置: &nbsp;&nbsp;</span>{{ item.camera_name }}
            </div>
            <div class="popup-tips" v-if="item.deptName">
              <span style="font-weight: bold; color: #333">船舶名称: &nbsp;&nbsp;</span>{{ item.deptName }}
            </div>
            <div @click.stop="clickVideo(item)" class="popup-video">查看视频（视频为告警时间前后5秒）</div>
          </div>
        </div>
        <div class="empty-content" v-else>
          <el-empty description="暂无数据" style="text-align: center; width: 100%; margin: 0 auto"></el-empty>
        </div>
      </div>
      <div v-else style="width: 100%;">
        <el-table :data="alarmPopupList" :height="winHeight" style="width: 100%" header-row-class-name="table-header">
          <el-table-column prop="deptName" label="船舶名称" min-width="180"></el-table-column>
          <el-table-column prop="mmsi" label="船舶MMSI" min-width="180"></el-table-column>
          <el-table-column prop="nmmsi" label="NMMSI号" min-width="180"></el-table-column>
          <el-table-column prop="camera_id" label="摄像头编码" min-width="180"></el-table-column>
          <el-table-column prop="camera_name" label="摄像头位置" min-width="180"></el-table-column>
          <el-table-column prop="state" label="告警状态" min-width="180">
            <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium" v-if="scope.row.state === 1">正常</el-tag>
                  <el-tag size="medium" type="info" v-else>误检</el-tag>
                </div>
              </template>
          </el-table-column>
          <el-table-column prop="state" label="告警处置状态" min-width="180">
            <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium" v-if="scope.row.processState === 1">已处置</el-tag>
                  <el-tag size="medium" type="warning" v-else-if="scope.row.processState === 2">超时已处置</el-tag>
                  <el-tag size="medium" type="danger" v-else>未处置</el-tag>
                </div>
              </template>
          </el-table-column>
          <el-table-column prop="algorithm_id" label="告警编码" min-width="180"></el-table-column>
          <el-table-column prop="algorithm_name" label="告警类型" min-width="180"></el-table-column>
          <el-table-column prop="level" label="告警等级" min-width="180"></el-table-column>
          <el-table-column prop="alarm_dt" label="告警时间" min-width="180"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="180"></el-table-column>
          <el-table-column label="操作" min-width="180" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click.stop="clickVisibleImgae(scope.row)">详情</el-button>
              <el-button type="text" @click.stop="clickFeedback(scope.row)" v-if="scope.row.state == 1">反馈</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination
      style="float: right; margin-top: 12px;"
      @size-change="handleSizeChange"
      @current-change="currentChange"
      :current-page="select.page"
      :page-size="select.count"
      :page-sizes="isTable ? [15, 25, 35, 50] : [8, 16, 32, 64]"
      layout="total, sizes, prev, pager, next"
      :total="select.total">
    </el-pagination>
    <el-dialog title="告警信息" width="1000px" :visible.sync="dialogImgaeVisible">
      <MarkDetail :alarmInfo="alarmInfo" :fileUrl="imageBase64" :filePath="filePath" :dataList="boxList" :ratio="1" :dataListAll="roiList" pageType="detail" />
    </el-dialog>
    <!-- 反馈popup -->
    <el-dialog title="一键反馈" width="800px" :visible.sync="feedbackVisible">
      <el-form :model="feedbackForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="feedbackForm.state" style="width: 100%;" placeholder="请选择状态">
            <el-option label="正常" value="1"></el-option>
            <el-option label="误检" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="4" v-model="feedbackForm.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="feedbackVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import MarkDetail from "./common/markDetail.vue";

import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
  export default {
    name: "alarm",
    components: {
      MarkDetail,
    },
    data() {
      return {
        winHeight: window.innerHeight - 200,
        feedbackForm: {
          id: '',
          state: '2',
          remark: '',
        },
        feedbackVisible: false, //反馈popup
        domain: JSON.parse(localStorage.getItem("userInfo")).domain + "/wvp/",
        videoDomain: JSON.parse(localStorage.getItem("userInfo")).domain + "/wvp-video/",
        filePath: '',
        fullscreenLoading: false,
        select: {
          total: 0,
          page: 1,
          count: 15,
          date: [],
          beginTime: "",
          endTime: "",
          deptName: "",
          algorithmName: "",
          mmsi: "",
          algorithmId: "",
          cameraName: "",
          level: "",
          state: "",
        },
        boxList: [],
        roiList: [],
        imageBase64: "",
        dialogImgaeVisible: false,
        shipOptions: [],
        typeOptions: [],
        alarmPopupList: [],
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一年",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
        alarmInfo: {},
        stateOptions: [
          { value: "0", label: "全部" },
          { value: "1", label: "正常" },
          { value: "2", label: "误检" },
        ],
        levelOptions: [
          { value: "全部", label: "全部" },
          { value: "低风险", label: "低风险" },
          { value: "中风险", label: "中风险" },
          { value: "高风险", label: "高风险" },
        ],
        isTable: true,
      };
    },
    mounted() {
      this.getShipsList();
      this.clickSelect();
      this.getAlgorithm();
      // this.getLevelOptions();
    },
    methods: {
      exportExcel() {
      // 1. 提取表格数据
      const data = this.alarmPopupList.map((row) => ({
        船舶名称: row.deptName,
        船舶MMSI: row.mmsi,
        NMMSI号: row.nmmsi,
        摄像头编码: row.camera_id,
        告警编码: row.algorithm_id,
        告警类型: row.algorithm_name,
        告警等级: row.level,
        告警时间: row.alarm_dt,
        创建时间: row.createTime,
      }));

      // 2. 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(data);

      // 3. 创建工作簿
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "表格数据");

      // 4. 生成 Excel 并下载
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });

      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      saveAs(blob, "表格数据.xlsx");
      },
      handleTypeView(type) {
        this.isTable = type;
        this.select.count = this.isTable ? 15 : 8;
        this.clickSelect();
      },
      currentChange: function (val) {
        this.select.page = val;
        this.clickSelect();
      },
      handleSizeChange: function (val) {
        this.select.count = val;
        this.clickSelect();
      },
      // 获取动态等级列表
      getLevelOptions() {
        const that = this;
        that.$axios({
          method: "get",
          url: `/api/message/get-all-level`,
        })
        .then((res) => {
          const data = res.data.data;
          that.levelOptions.push({
            value: "全部",
            label: "全部",
          })
          data.forEach((item) => {
            that.levelOptions.push({
              value: item,
              label: item,
            })
          })
        })
        .catch((error) => {
          console.log(error);
        })
        .catch((error) => {
          console.log(error);
        });
      },
      // 获取动态告警列表
      getAlgorithm() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/get-all-algorithm`,
            params: {},
          })
          .then((res) => {
            console.log(res);
            const data = res.data.data;
            that.typeOptions.push({
              value: "全部",
              label: "全部",
            })
            data.forEach((item) => {
              that.typeOptions.push({
                value: item,
                label: item,
              })
            })
          })
          .catch((error) => {
            console.log(error);
          })
          .catch((error) => {
            console.log(error);
          });
      },
      clickFeedback(item) {
        this.feedbackForm.id = item.id;
        this.feedbackForm.remark = '';
        this.feedbackForm.state = '2';
        this.feedbackVisible = true;
      },
      // 反馈弹窗确定按钮
      submitForm() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/message/update-state?id=${that.feedbackForm.id}&state=${that.feedbackForm.state}&remark=${that.feedbackForm.remark}`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              that.$message.success("反馈成功!");
              setTimeout(() => {
                that.clickSelect();
              }, 500);
            }
            that.feedbackVisible = false;
          });
        console.log(that.feedbackForm)
      },
      // 查看视频
      clickVideo(item) {
        const that = this;
        if (item.filePath === '' || item.filePath == null) {
          this.$message.error("暂无视频!");
          return
        }
        window.open(this.videoDomain + item.filePath, "_blank");
        return;
        // 定义初始时间
        const initialTime = new Date(item.alarm_dt);

        // 获取前后5秒的时间
        const beforeTime = new Date(initialTime.getTime() - 4000); // 减去4000毫秒
        const afterTime = new Date(initialTime.getTime() + 4000); // 加上4000毫秒

        // 格式化时间
        const formatTime = (date) => {
          const pad = (num) => (num < 10 ? "0" + num : num);
          return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
            date.getDate()
          )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
            date.getSeconds()
          )}`;
        };
        let startTime = formatTime(beforeTime);
        let endTime = formatTime(afterTime);
        that
          .$axios({
            method: "get",
            url: `/api/department/box/channel?boxId=${item.box_id}&name=${item.camera_name}`,
          })
          .then((res) => {
            if (res.data.data == null) {
              this.$message.error("未找到对应通道!");
              return;
            }
            that.getPlayback(res.data.data, startTime, endTime);
          });
      },
      getPlayback(data, startTime, endTime) {
        const that = this;
        const loading = this.$loading({
          lock: true,
          text: "正在加载中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        that
          .$axios({
            method: "get",
            url: `/api/playback/start/${data.deviceId}/${data.channelId}?startTime=${startTime}&endTime=${endTime}`,
          })
          .then((res) => {
            loading.close();
            if (res.data.code != 0) {
              this.$message.error(res.data.msg);
              return;
            }

            window.open(res.data.data.fmp4, "_blank");
          });
      },
      clickVisibleImgae(item) {
        // this.imageBase64 = "data:image/png;base64," + item.imageBase64;
        this.imageBase64 = this.domain + item.img_name;
        this.filePath = item.filePath ? this.videoDomain + item.filePath : "";
        this.boxList = JSON.parse(item.params);
        this.dialogImgaeVisible = true;
        this.alarmInfo = item
      },
      clickReset() {
        this.select = {
          total: 0,
          page: 1,
          count: 15,
          date: [],
          beginTime: "",
          endTime: "",
          deptName: "",
          algorithmName: "",
          mmsi: "",
          algorithmId: "",
          cameraName: "",
          level: "",
          state: "",
        };
        this.select.count = this.isTable ? 15 : 8;
        this.clickSelect();
      },
      clickSelect() {
        const that = this;
        let beginTime = this.getNowFormatDate();
        let endTime = this.getNowFormatDate();
        if (that.select.date.length > 0) {
          beginTime = that.select.date[0];
          endTime = that.select.date[1];
        }
        const loading = this.$loading({
          lock: true,
          text: "正在获取中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        that.$set(that.select, "date", [beginTime, endTime])
        const params = {  ...that.select, beginTime, endTime };
        delete params.date;
        delete params.total;
        that
          .$axios({
            method: "get",
            url: `/api/message/list`,
            params,
          })
          .then((res) => {
            loading.close();
            if (res.data.code == 0) {
              that.alarmPopupList = res.data.data.list;
              that.select.total = res.data.data.total;
              return;
            }
            that.$message.error(res.data.msg);
          });
      },
      // 获取当前年月日
      getNowFormatDate() {
        // 获取当前的日期
        let today = new Date();

        // 获取年份、月份和日期
        let year = today.getFullYear();
        let month = String(today.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以需要加1
        let day = String(today.getDate()).padStart(2, "0");

        // 创建当前的日期字符串
        let todayString = `${year}-${month}-${day}`;
        return todayString;
      },
      // 分页
      pagingDepartment(val) {
        this.select.page = val;
        this.clickSelect();
      },
      // 获取船舶列表
      getShipsList() {
        const that = this;
        that
          .$axios({
            method: "get",
            url: `/api/department/dept/ships?page=1&count=999&kinds=1`,
          })
          .then((res) => {
            if (res.data.code == 0) {
              that.shipOptions = res.data.data.list;
              // res.data.data.list.forEach((item) => {
              //     that.shipOptions.push({
              //         value: item.id,
              //         label: item.deptName,
              //     });
              // })
            }
          })
          .catch((error) => {
            console.log(error);
          });
      },
    },
  };
</script>
<style scoped>
  .head-card-icon-box {
    padding-right: 16px;
    width: 100%;
    text-align: right;
  }
  .active {
    color: #409EFF;
  }
  .el-icon-s-fold,
  .el-icon-s-grid {
    font-size: 20px;
  }
  .el-icon-s-fold:hover,
  .el-icon-s-grid:hover {
    color: #409EFF;
  }
  .el-icon-s-fold {
    margin-right: 10px;
  }
  .head-card {
    display: flex;
    flex-wrap: wrap;
  }

  .card-content {
    width: 100%;
    margin-top: 20px;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    overflow: hidden;
    color: #303133;
    -webkit-transition: 0.3s;
    transition: 0.3s;
    padding-top: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .paging-content {
    width: 100%;
    margin-top: 20px;
    margin-bottom: 10px;
    text-align: right;
  }

  .empty-content {
    width: 100%;
    border: 1px solid #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 80px;
    text-align: center;
  }

  .content {
    width: 100%;
  }

  .box-card {
    width: 100%;
    margin-top: 20px;
  }

  .select-card {
    display: flex;
  }

  .alarm-popup {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    border: 1px solid #fff;
    padding: 0 10px;
    margin-top: 12px;
  }

  .alarm-popup .popup-item {
    width: 24%;
    margin: 0 0.5% 20px;
    height: auto;
    border-radius: 6px;
    overflow: hidden;
    padding-bottom: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  .alarm-popup .popup-item img {
    width: 100%;
    height: 200px;
  }

  .alarm-popup .popup-item .popup-title {
    font-weight: 500;
    font-size: 16px;
    color: #333;
    display: flex;
    margin-top: 8px;
    padding-left: 10px;
  }

  .alarm-popup .popup-item .popup-tips {
    font-size: 12px;
    line-height: 22px;
    display: flex;
    padding-left: 10px;
    color: #909399;
  }

  .alarm-popup .popup-item .popup-video {
    color: #003bb1;
    font-size: 12px;
    line-height: 22px;
    display: flex;
    padding-left: 10px;
  }
  .text-align-start {
    text-align: start;
    padding-bottom: 8px;
  }
  .common-style {
    margin-right: 10px;
    width: auto;
    margin-top: 10px;
  }
</style>
